#include "BCNICStatus.h"

//************************************
// Method:    	BCNIC_PACK_Make				打包程序
// Programmer:  lww
// Time:		2019/2/16
// Returns:   	int							打包字节数
// Parameter: 	void * Data					数据区头指针
// Parameter: 	short Head					报头
// Parameter: 	short Tail					报尾
//************************************
int BCNIC_PACK_Make(void* Data, short Head, short Tail)
{
#define MEMWRITE1(name)	MEMWRITE(name, Data);
	int _iLen = 0;


	//< 报头
	MEMWRITE1(Head);	

	//< 报尾
	MEMWRITE1(Tail);
	return _iLen;
}


//************************************
// Method:    	tBCNICStatus			广播NIC状态
// Programmer:  lww
// Time:		2018/12/22
// Returns:   	void *
// Parameter: 	void * arg
//************************************
void *tBCNICStatus(void* arg)
{
#define PACK_MAXNUM	2048
	//int sock;

	int sock_b;
	int sock_d;
	struct sockaddr_in NetD;
	timer_t BCDPU_Timer;
	struct timespec time;
	short Head = 2022;				//< 报头
	short Tail = 0113;				//< 报尾
	char Data2Send[PACK_MAXNUM];	//< 存放数据包的数组
	int _iLen = 0;
	printf("sock_d is %d\n",sock_d);
	printf("the Kernel_%s is %d\r\n", "tBCNICStatus_ID", syscall(SYS_gettid));			//< duan20200610

	//< 初始化UDP设置
	//if (false == UDP_Init(&sock, BCDPU_PORT, 0, 0, UDP_SEND_STATUS, nullptr)) { return 0; }
	if (false == UDP_Init(&sock_d, BCNIC_PORT, 0, 0, UDP_SEND_STATUS, NETD_IP_BC_LOCAL)) { return 0; }

	//< 设置发送到的IP地址及端口

	Addr_Set(&NetD, BCNIC_PORT, inet_addr(NETA_IP_BC));//不要和BCDPU用同一个端口
	
	//< 设置广播周期
	MS2TimeSpec(&time, BCNIC_PERIOD);

	//< 开启定时中断
	Timer_Create(&BCDPU_Timer, BcDPUSIG, &time);
	while (1)
	{
		RoughDelay_S(1);
		//< 等待信号量释放进行广播操作
		/*MUTEX_LOCK(BcDPU_Mutex, "BcDPU_Mutex lock failed");*/
		SEM_WAIT(BcDPUSemId, "BcDPUSemId wait failed");

		//< 数据打包
		_iLen = BCNIC_PACK_Make(Data2Send, Head, Tail);

		//< 发送数据
		if (-1 == UDP_Send(&sock_d, &NetD, (char*)Data2Send, _iLen))
		{
			SYS_NetD_Status = Net_Trouble;
		}
		else
		{
			SYS_NetD_Status = Net_Normal;
		}
	}
	//close(sock);//< 断开连接
	close(sock_d);//< 断开连接
#undef PACK_MAXNUM
}
